<template>
  <div class="chat-window">
    <div class="chat-header">
      <div class="chat-user-info">
        <el-avatar :size="40" :src="chatUser.avatar" :icon="'User'" />
        <div class="user-details">
          <div class="user-name">{{ chatUser.name }}</div>
          <div class="user-status" :class="{ online: chatUser.isOnline }">
            {{ chatUser.isOnline ? '在线' : '离线' }}
          </div>
        </div>
      </div>
      <div class="chat-actions">
        <el-button size="small" type="info" @click="handleClearHistory">
          清空记录
        </el-button>
        <el-button size="small" @click="$emit('close')">
          关闭
        </el-button>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div
        v-for="message in messages"
        :key="message.id"
        class="message-wrapper"
        :class="{ 'own-message': message.isOwn }"
      >
        <div class="message-avatar">
          <el-avatar
            :size="32"
            :src="message.isOwn ? currentUser.avatar : chatUser.avatar"
            :icon="'User'"
          />
        </div>
        <div class="message-content">
          <div class="message-info">
            <span class="sender-name">
              {{ message.isOwn ? currentUser.name : chatUser.name }}
            </span>
            <span class="message-time">{{ formatTime(message.createTime) }}</span>
          </div>
          <div class="message-bubble" :class="{ 'own-bubble': message.isOwn }">
            <div class="message-text">{{ message.content }}</div>
            <div v-if="message.images && message.images.length > 0" class="message-images">
              <el-image
                v-for="image in message.images"
                :key="image.id"
                :src="image.url"
                :preview-src-list="message.images.map(img => img.url)"
                class="message-image"
                fit="cover"
              />
            </div>
          </div>
          <div v-if="message.status" class="message-status">
            <el-icon v-if="message.status === 'sending'" class="is-loading">
              <Loading />
            </el-icon>
            <el-icon v-else-if="message.status === 'sent'" color="#67c23a">
              <Check />
            </el-icon>
            <el-icon v-else-if="message.status === 'read'" color="#409eff">
              <CircleCheck />
            </el-icon>
            <el-icon v-else-if="message.status === 'failed'" color="#f56c6c">
              <Close />
            </el-icon>
          </div>
        </div>
      </div>
      
      <!-- 正在输入提示 -->
      <div v-if="isTyping" class="typing-indicator">
        <div class="typing-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
        <span class="typing-text">{{ chatUser.name }} 正在输入...</span>
      </div>
    </div>

    <div class="chat-input">
      <div class="input-toolbar">
        <el-button size="small" type="text" @click="showEmojiPicker = !showEmojiPicker">
          😊
        </el-button>
        <el-upload
          :show-file-list="false"
          :before-upload="handleImageUpload"
          accept="image/*"
        >
          <el-button size="small" type="text">📷</el-button>
        </el-upload>
      </div>
      
      <!-- 表情选择器 -->
      <div v-if="showEmojiPicker" class="emoji-picker">
        <div class="emoji-grid">
          <span
            v-for="emoji in emojis"
            :key="emoji"
            class="emoji-item"
            @click="insertEmoji(emoji)"
          >
            {{ emoji }}
          </span>
        </div>
      </div>

      <div class="input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="输入消息..."
          @keydown.enter.exact="handleSendMessage"
          @keydown.enter.shift.exact.prevent="inputMessage += '\n'"
          @input="handleTyping"
        />
        <el-button
          type="primary"
          :disabled="!inputMessage.trim()"
          @click="handleSendMessage"
          class="send-button"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, Check, CircleCheck, Close } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  chatUser: {
    type: Object,
    required: true
  },
  currentUser: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits(['close', 'send-message'])

// 响应式数据
const messagesContainer = ref(null)
const inputMessage = ref('')
const messages = ref([])
const isTyping = ref(false)
const showEmojiPicker = ref(false)
const typingTimer = ref(null)

// 表情列表
const emojis = ref([
  '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
  '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
  '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
  '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
  '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬'
])

// 方法
const formatTime = (time) => {
  const date = new Date(time)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const handleSendMessage = () => {
  if (!inputMessage.value.trim()) return
  
  const message = {
    id: Date.now(),
    content: inputMessage.value.trim(),
    createTime: new Date(),
    isOwn: true,
    status: 'sending'
  }
  
  messages.value.push(message)
  inputMessage.value = ''
  scrollToBottom()
  
  // 模拟发送状态变化
  setTimeout(() => {
    message.status = 'sent'
  }, 1000)
  
  setTimeout(() => {
    message.status = 'read'
  }, 2000)
  
  emit('send-message', message)
}

const handleTyping = () => {
  // 清除之前的定时器
  if (typingTimer.value) {
    clearTimeout(typingTimer.value)
  }
  
  // 设置新的定时器
  typingTimer.value = setTimeout(() => {
    // 停止输入状态
  }, 1000)
}

const insertEmoji = (emoji) => {
  inputMessage.value += emoji
  showEmojiPicker.value = false
}

const handleImageUpload = (file) => {
  // 处理图片上传
  const reader = new FileReader()
  reader.onload = (e) => {
    const message = {
      id: Date.now(),
      content: '',
      images: [{
        id: Date.now(),
        url: e.target.result
      }],
      createTime: new Date(),
      isOwn: true,
      status: 'sending'
    }
    
    messages.value.push(message)
    scrollToBottom()
    
    // 模拟上传完成
    setTimeout(() => {
      message.status = 'sent'
    }, 1000)
  }
  reader.readAsDataURL(file)
  
  return false // 阻止默认上传
}

const handleClearHistory = () => {
  messages.value = []
  ElMessage.success('聊天记录已清空')
}

// 模拟接收消息
const simulateReceiveMessage = () => {
  const responses = [
    '您好，有什么可以帮助您的吗？',
    '好的，我明白了',
    '请稍等，我查看一下',
    '这个房源确实不错',
    '我们可以约个时间看房'
  ]
  
  setTimeout(() => {
    const message = {
      id: Date.now(),
      content: responses[Math.floor(Math.random() * responses.length)],
      createTime: new Date(),
      isOwn: false
    }
    
    messages.value.push(message)
    scrollToBottom()
  }, Math.random() * 3000 + 1000)
}

// 生命周期
onMounted(() => {
  // 模拟一些历史消息
  messages.value = [
    {
      id: 1,
      content: '您好，我对您发布的房源很感兴趣',
      createTime: new Date(Date.now() - 3600000),
      isOwn: true,
      status: 'read'
    },
    {
      id: 2,
      content: '您好，欢迎咨询！这套房子位置很好，配套设施齐全',
      createTime: new Date(Date.now() - 3500000),
      isOwn: false
    },
    {
      id: 3,
      content: '可以约个时间看房吗？',
      createTime: new Date(Date.now() - 3400000),
      isOwn: true,
      status: 'read'
    }
  ]
  
  scrollToBottom()
})
</script>

<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 600px;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.chat-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-name {
  font-weight: 600;
  color: #2c3e50;
}

.user-status {
  font-size: 12px;
  color: #909399;
}

.user-status.online {
  color: #67c23a;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f8f9fa;
}

.message-wrapper {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
  gap: 8px;
}

.message-wrapper.own-message {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
}

.message-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 12px;
  color: #909399;
}

.own-message .message-info {
  flex-direction: row-reverse;
}

.message-bubble {
  background: #fff;
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-bubble.own-bubble {
  background: #409eff;
  color: #fff;
}

.message-text {
  line-height: 1.4;
  word-break: break-word;
}

.message-images {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.message-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  cursor: pointer;
}

.message-status {
  text-align: right;
  margin-top: 4px;
}

.own-message .message-status {
  text-align: left;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 12px;
}

.typing-dots {
  display: flex;
  gap: 2px;
}

.typing-dots span {
  width: 4px;
  height: 4px;
  background: #909399;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

.chat-input {
  border-top: 1px solid #ebeef5;
  background: #fff;
}

.input-toolbar {
  padding: 8px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  gap: 8px;
}

.emoji-picker {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 8px;
}

.emoji-item {
  font-size: 20px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  text-align: center;
  transition: background-color 0.2s;
}

.emoji-item:hover {
  background: #e6f7ff;
}

.input-area {
  padding: 16px;
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.input-area .el-textarea {
  flex: 1;
}

.send-button {
  height: 40px;
}
</style>
